<?php
class FileController extends Zend_Controller_Action 
{
	public function indexAction()
	{
		$this->_redirect('/file/list/');
	}

	public function listAction()
	{
		$this->_checkUploadFile();
		$this->_checkCreateDir();
		$root = new Data_Directory(App_Config::FILEREPOSITORY );
		$dir = $this->_getDirectory();
		$view = new Zend_View();
		$view->setScriptPath(App_Config::VIEWPATH);
		$view->addHelperPath(App_Config::HELPERPATH);
		$view->dir = $dir;
		$view->root = $root;
		$view->isRoot = ($root->getFilePath()==$dir->getFilePath());
		echo $view->render('listdir.php');
	}

	public function viewAction()
	{
		$file = $this->_getFile();
		$file->send();
	}

	public function thumbAction()
	{
		$file = $this->_getFile();
		$file->sendThumb();
	}

	public function noRouteAction()
	{
		$this->_redirect('/file/list/');
	}
	
	protected function _getDirectory()
	{
		$path = App_Config::FILEREPOSITORY;
		foreach ($this->_getAllParams() as $key=>$value) {
			$path.= DIRECTORY_SEPARATOR.urldecode($key);
			$path.= DIRECTORY_SEPARATOR.urldecode($value);
		}
		return new Data_Directory($path);
	}

	protected function _getFile()
	{
		$path = App_Config::FILEREPOSITORY;
		foreach ($this->_getAllParams() as $key=>$value) {
			$path.= DIRECTORY_SEPARATOR.urldecode($key);
			if ($value!='') {
				$path.= DIRECTORY_SEPARATOR.urldecode($value);
			}
		}
		return new Data_File($path);
	}
	
	protected function _checkUploadFile() {
		if (key_exists('file',$_FILES)) {
			$fileInput = new Zend_Filter_Input($_FILES['file']);
			if ($fileInput->getInt('size')) {
				$tmpFile = new Data_File($fileInput->getPath('tmp_name'));
				$fileName = $tmpFile->getFilename();
				$dir = $this->_getDirectory();
				$tmpFile->moveTo($dir);
				$newFile = $dir->getFile($fileName);
				$newFile->rename(utf8_decode($fileInput->getRaw('name')));
			}
		}
	}
	
	protected function _checkCreateDir() {
		$input = new Zend_Filter_Input($_POST);
		if ($input->testRegex('dirname','/^[^\/\\\\":*?<>|]+$/')) {
			$dirname = $input->getRaw('dirname');
			$dir = $this->_getDirectory();
			$dir->createDir(utf8_decode($dirname));
		}
	}
}

?>